package felix.rule.web;


import felix.rule.data.plugin.ComponentDescriptor;
import felix.rule.data.plugin.ComponentType;
import felix.rule.service.ComponentDiscoveryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
@RequestMapping("/api")
@Slf4j
public class ComponentDescriptorController {

    @Autowired
    protected ComponentDiscoveryService componentDescriptorService;

    @RequestMapping(value = "/component/{componentDescriptorClazz:.+}", method = RequestMethod.GET)
    public ComponentDescriptor getComponentDescriptorByClazz(@PathVariable("componentDescriptorClazz") String strComponentDescriptorClazz) {
        try {
            Optional<ComponentDescriptor> component = componentDescriptorService.getComponent(strComponentDescriptorClazz);
            if (component.isPresent()) {
                return component.get();
            } else {
                throw new NoSuchElementException("Requested item wasn't found!");
            }
        } catch (Exception e) {
            log.error("Error [{}]", e.getMessage(), e);
            throw e;
        }
    }

    @RequestMapping(value = "/components/{componentType}", method = RequestMethod.GET)
    public List<ComponentDescriptor> getComponentDescriptorsByType(@PathVariable("componentType") String strComponentType) {
        try {
            return componentDescriptorService.getComponents(ComponentType.valueOf(strComponentType));
        } catch (Exception e) {
            log.error("Error [{}]", e.getMessage(), e);
            throw e;
        }
    }

    @RequestMapping(value = "/components", params = {"componentTypes"}, method = RequestMethod.GET)
    public List<ComponentDescriptor> getComponentDescriptorsByTypes(@RequestParam("componentTypes") String[] strComponentTypes) {
        try {
            Set<ComponentType> componentTypes = new HashSet<>();
            for (String strComponentType : strComponentTypes) {
                componentTypes.add(ComponentType.valueOf(strComponentType));
            }
            return componentDescriptorService.getComponents(componentTypes);
        } catch (Exception e) {
            log.error("Error [{}]", e.getMessage(), e);
            throw e;
        }
    }

}
